package problem703;

import java.util.PriorityQueue;

//703.数据流中的第k大的元素
//https://leetcode.cn/problems/kth-largest-element-in-a-stream/

class KthLargest {
    PriorityQueue<Integer> queue;
    int k = 0;
    public KthLargest(int k, int[] nums) {
        queue = new PriorityQueue<>();
        this.k = k;
        for(int x : nums) {
            if(queue.size() < k) queue.add(x);
            else if(x > queue.peek()){
                queue.poll();
                queue.add(x);
            }
        }
    }
    public int add(int val) {
        if(queue.size() < k) queue.add(val);
        else if(val > queue.peek()) {
            queue.poll();
            queue.add(val);
        }
        return queue.peek();
    }
}

/**
 * Your KthLargest object will be instantiated and called as such:
 * KthLargest obj = new KthLargest(k, nums);
 * int param_1 = obj.add(val);
 */